package model.primefactor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Created by andreas on 20.04.14.
 */
public class PrimefactorGenerator {

    public List<Integer> generatePrimefactors(int i) {
        if (i == 1) {
            return new ArrayList<Integer>();
        }
        List<Integer> primeFactors = generatePrimefactorsRecursiv(i);
        Collections.sort(primeFactors);
        return primeFactors;
    }

    private List<Integer> generatePrimefactorsRecursiv(int i) {
        final Integer largestDivider = largestDivider(i);
        if (largestDivider == i) {
            final List<Integer> list = new ArrayList<Integer>();
            list.add(largestDivider);
            return list;
        } else {
            final int factor1 = largestDivider;
            final int factor2 = i / largestDivider;
            final List<Integer> primes1 = generatePrimefactors(factor1);
            final List<Integer> primes2 = generatePrimefactors(factor2);
            primes1.addAll(primes2);
            return primes1;
        }
    }

    private int largestDivider(int dividend) {
        for (int i=dividend-1; i>2; i--) {
            if (dividend % i == 0) {
                return i;
            }
        }
        return dividend;
    }

}
